document.addEventListener('DOMContentLoaded', () => {
    const dropZone = document.getElementById('drop-zone');
    const fileInput = document.getElementById('file-input');
    const browseBtn = document.getElementById('browse-btn');
    const messageArea = document.getElementById('message-area');
    const downloadArea = document.getElementById('download-area');
    const uploadForm = document.getElementById('upload-form');

    // Open file dialog when browse button is clicked
    browseBtn.addEventListener('click', () => {
        fileInput.click();
    });

    // Open file dialog when drop zone is clicked
    dropZone.addEventListener('click', () => {
        fileInput.click();
    });

    // Handle file input change
    fileInput.addEventListener('change', () => {
        if (fileInput.files.length > 0) {
            handleFile(fileInput.files[0]);
        }
    });

    // Drag and drop events
    dropZone.addEventListener('dragover', (e) => {
        e.preventDefault();
        dropZone.classList.add('dragover');
    });

    dropZone.addEventListener('dragleave', () => {
        dropZone.classList.remove('dragover');
    });

    dropZone.addEventListener('drop', (e) => {
        e.preventDefault();
        dropZone.classList.remove('dragover');
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            handleFile(files[0]);
        }
    });

    function handleFile(file) {
        if (file.name.split('.').pop().toLowerCase() !== 'ipynb') {
            showMessage('Error: Please select a .ipynb file.', 'error');
            return;
        }

        uploadFile(file);
    }

    function uploadFile(file) {
        const formData = new FormData();
        formData.append('file', file);

        showMessage('Uploading and converting...', 'info');
        downloadArea.innerHTML = '';

        fetch('/upload', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                showMessage(`Error: ${data.error}`, 'error');
            } else if (data.download_url) {
                showMessage('Conversion successful!', 'success');
                const link = document.createElement('a');
                link.href = data.download_url;
                link.textContent = 'Download PDF';
                link.setAttribute('download', '');
                downloadArea.appendChild(link);
            }
        })
        .catch(error => {
            showMessage(`An unexpected error occurred: ${error}`, 'error');
        });
    }

    function showMessage(message, type) {
        messageArea.innerHTML = `<p class="${type}">${message}</p>`;
    }
});
